package com.varian.task.core;

import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.thread.ExecutorBuilder;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

/**
 * @author ben
 * @since 2024/12/31
 */
public class TaskThreadPool {

    private ExecutorService executor;

    public TaskThreadPool(Integer executeBlockStrategy) {
        init(executeBlockStrategy);
    }

    public void init(Integer executeBlockStrategy) {
        ExecutorBuilder builder = ExecutorBuilder.create()
                .useArrayBlockingQueue(10)
                .setAllowCoreThreadTimeOut(true);
        if (executeBlockStrategy > 0) {
            builder.setMaxPoolSize(executeBlockStrategy);
        }
        this.executor = builder.build();
    }

    public void shutdown(boolean isNow) {
        if (null != this.executor) {
            if (isNow) {
                this.executor.shutdownNow();
            } else {
                this.executor.shutdown();
            }
        }
    }

    public void execute(Runnable runnable) {
        try {
            this.executor.execute(runnable);
        } catch (Exception e) {
            throw new UtilException(e, "Exception when running task!");
        }
    }

    public <T> Future<T> submit(Callable<T> task) {
        return executor.submit(task);
    }

    public Future<?> submit(Runnable runnable) {
        return executor.submit(runnable);
    }
}
